package com.wm.blog_web.controller;

import com.google.code.kaptcha.Producer;
import com.wm.blog_web.controller.base.WebBaseController;
import com.wm.blog_web.service.TUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author ：wm_yu
 * @description : 验证码生成
 * @createTime ：2020/4/6
 */
@RestController
@RequestMapping("/web/code")
@AllArgsConstructor
@Slf4j
public class ValidateCodeController extends WebBaseController {


    private final Producer producer;

   private final TUserService userService;



    @GetMapping("/getCode")
    public void getCode(String random, HttpServletResponse response) throws IOException {
        if(StringUtils.isEmpty(random)){
            log.warn("生成验证码随机数必须");
            return;
        }
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        // 生成文字验证码
        String text = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);
        userService.saveImageCode(random, text);
        try (ServletOutputStream out = response.getOutputStream()) {
            ImageIO.write(image, "JPEG", out);
        }
    }

}
